home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 10265 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.4 KB  |  58 lines

  1. Path: locutus.rchland.ibm.com!usenet
  2. From: Philip Staite <pstaite+@rchland.ibm.com>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: random numbers in visual C++
  5. Date: Thu, 07 Mar 1996 07:40:20 -0600
  6. Organization: IBM Rochester, MN
  7. Message-ID: <313EE744.2781@rchland.ibm.com>
  8. References: <4hfusd$916@eddie.intr.net>
  9. NNTP-Posting-Host: powertool.rchland.ibm.com
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.0 (X11; I; AIX 1)
  14.  
  15. willodk@intr.net wrote:
  16. > How can I generate random numbers in Visual C++ (version 1.52) between 0 and 100?  How is the RAND_MAX
  17. > set?
  18.  
  19. Try this:
  20.  
  21.  
  22. #include<stdlib.h>
  23. #include<time.h>
  24.  
  25.  
  26. // one time initialization somewhere in your code
  27. srand( time( 0 ) );
  28.  
  29.  
  30. //
  31. // gen rand number between lo and hi (inclusive)
  32. //
  33. int rangen( int lo, int hi );
  34.  
  35.  
  36. int rangen( int lo, int hi ) {
  37.     return lo + ( rand() % ( hi - lo + 1 ) ); }
  38.  
  39.  
  40. Then you could call this function as:
  41.  
  42. int myrand = rangen( 0, 100 );
  43.  
  44. Which would give you numbers between 0 and 100 inclusive.
  45.  
  46. Before any other comp-sci types jump on this, yes, most system supplied
  47. rand()'s are not that great at producing good _sequences_ of random
  48. numbers.  And yes, simple modulo is not a good way to map down
  49. 0..RAND_MAX to lo..hi -- but it's quick and easy ;-)
  50.  
  51.  
  52.  
  53. -- 
  54.  
  55. Phil Staite, (507) 253-2529, team OS/2
  56. internet: pstaite@vnet.ibm.com  internal: pstaite@rchland
  57.